package org.example;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 验证没有加锁出现的问题， 阻塞队列初步
 */
public class TestThreadUnsafe {

    private final int[] array = new int[10];
    private int tail;
    private int size;

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public boolean offer(int x) throws InterruptedException {
//        lock.lock();
        lock.lockInterruptibly();
        try {
//            if (isFull()) {
            while (isFull()) {
                condition.await();
            }
            array[tail] = x;
            tail++;
        } finally {
            lock.unlock();
        }
        return true;
    }

    public static void main(String[] args) {
        TestThreadUnsafe test = new TestThreadUnsafe();
        new Thread(() -> {
            try {
                test.offer(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1").start();
        new Thread(() -> {
            try {
                test.offer(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t2").start();

    }

    public boolean isFull() {
        return size == array.length;
    }

    public boolean isEmpty() {
        return size == 0;
    }
}
